
<template>
  <div class="app-container">
    <search-header
      v-show="boo.showSearch"
      :select-prop="selectProp"
      @search-action="searchAction"
    ></search-header>
    <div class="app-permission-container flex-between mb8">
      <span class="page-list-title">活动列表</span>
      <div class="action-content">
        <el-button v-hasPermi="['shop:acddActivity:add']" type="primary" size="mini" @click="jumpPage('actionActive')"
        >新建活动</el-button>
        <el-button :disabled="boo.multiple" type="primary" size="mini" @click="fetchBatchPrice"
        >批量支付</el-button>
      </div>
    </div>
    <div class="app-table-container">
      <el-table
        v-loading="boo.loading"
        @selection-change="handleSelectionChange"
        :data="list" border header-row-class-name="app-table-list"
      >
        <el-table-column 
          :selectable="selectEnable"
          type="selection" width="50" align="center" /> 
        <el-table-column
          label="活动编号"
          align="center"
          key="activityCode"
          prop="activityCode"
          :show-overflow-tooltip="true"/>
        <el-table-column
          label="活动类型"
          align="center"
          :show-overflow-tooltip="true"> 
          <template slot-scope="{row}">
            {{row.activityTypeId | numToStr(dictsList, 'activityTypeId')}}
          </template>
        </el-table-column>
        <el-table-column
          label="活动名称"
          align="center"
          :show-overflow-tooltip="true"> 
          <template slot-scope="{row}">
            {{row.activityName || '/'}}
          </template>
        </el-table-column>
        <el-table-column
          label="套餐内容"
          align="center"
          :show-overflow-tooltip="true"
          width="120"> 
          <template slot-scope="{row}">
            {{row.packageContent || '/'}}
          </template>
        </el-table-column>
        <el-table-column
          label="活动时间"
          align="center"
          :show-overflow-tooltip="true">
          <template slot-scope="{row}">
            <template v-if="row.startingTime">
              <div class="row-txt">开始时间： {{ row.startingTime }}</div>
              <div class="row-txt">结束时间： {{ row.endTime }}</div>
            </template>
            <template v-else> / </template>
          </template>
        </el-table-column>

        <el-table-column
          label="优惠价格(元)"
          align="center"> 
          <template slot-scope="{row}">
            {{row.preferentialPrice || '/'}}
          </template>
        </el-table-column>
        <el-table-column
          label="活动份数"
          align="center"
          :show-overflow-tooltip="true"> 
          <template slot-scope="{row}">
            {{row.number || '/'}}
          </template>
        </el-table-column>
        <el-table-column
          label="状态"
          align="center"
          key="activityStatus"
          prop="activityStatus"> 
          <template slot-scope="{row}">
            {{row.activityStatus | numToStr(dictsList, 'activityStatus')}}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="{row}">
            <el-button
              size="mini" v-if="row.activityStatus == '3'"
              type="text" v-hasPermi="['shop:acddActivity:view']"
              @click="jumpPage('actionActive',{id: row.id}, {})"
              >去支付</el-button
            >
            <el-button
              size="mini" v-if="hasEditBtn(row)"
              type="text" v-hasPermi="['shop:acddActivity:edit']"
              @click="jumpPage('editActive',{id: row.id}, {})"
              >编辑</el-button
            >
            <el-button
              size="mini" v-if="hasDetailBtn(row)"
              type="text"
              @click="jumpPage('detailActive',{id: row.id}, {})"
              >活动详情</el-button
            >
            <el-button
              size="mini" v-hasPermi="['shop:shop:acddActivity:retransmission']"
              type="text" v-if="row.activityStatus == '2'"
              @click="jumpPage('actionActive',{id: row.id, type: 'reset'}, {})"
              >重发</el-button
            >
            <el-button
              size="mini" v-hasPermi="['shop:acddActivity:getActivityImgUrl']"
              type="text" v-if="row.activityStatus == '1' && hasH5(row)"
              @click="showDialog('link', 'view', row)"
              :loading="row.isLink"
              >链接</el-button
            >
            <el-button
              size="mini" v-hasPermi="['shop:acddActivity:getActivityBrowseInfo']"
              type="text" v-if="row.activityStatus != '0' && hasH5(row)"
              @click="jumpPage('ActiveData',{}, {id: row.id})"
              >数据</el-button
            >
            <template v-if="row.activityTypeId != '7'">
              <el-button
                size="mini" v-hasPermi="['shop:acddActivity:getActivityImgUrl']"
                type="text" v-if="row.activityStatus == '1' && hasH5(row)"
                @click="jumpPage('ActiveH5',{}, {id: row.id})"
                >活动页设置</el-button
              >
            </template>
            <el-button
              size="mini" v-hasPermi="['shop:acddActivity:cease']"
              type="text" v-if="row.activityStatus == '1'"
              @click="stopRow(row)"
              >停止</el-button
            >
            <el-button
              size="mini" v-hasPermi="['shop:acddActivity:remove']"
              type="text" v-if="row.activityStatus != '1'"
              @click="delRow(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="other.total > 0"
        :total="other.total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <dialog-normal
      ref="dialog-link"
      :dialog-prop="{
        title: '推广链接',
        width: '40%',
        height: '50vh'
      }">
      <template #dialog-content v-if="$refs[`dialog-link`] && $refs[`dialog-link`].showDialog">
        <div class="dialog-link-content">
          <div class="item-row flex-normal">
            <span class="row-label">推广链接</span>
            <div class="row-content flex-normal">
              <span class="link-txt">{{ linkProp.currentItem['url'] }}</span>
            </div>
            <el-link :underline="false" class="row-btn" type="primary"
            v-clipboard:copy="linkProp.currentItem['url']"
            v-clipboard:success="clipboardSuccess">复制推广链接</el-link>
          </div>
          <div class="item-row flex-normal img" v-if="linkProp.currentItem['img'] && linkProp.currentItem['activityTypeId'] != 7">
            <span class="row-label">推广图片</span>
            <el-image class="row-img" :src="linkProp.currentItem['img']"></el-image>
            <el-link :underline="false" class="row-btn" type="primary" :href="linkProp.currentItem['img']">下载推广图片</el-link>
          </div>
        </div>
      </template>
    </dialog-normal>
    <dialog-normal
      ref="dialog-price"
      :dialog-prop="{
        title: '批量活动结算',
        height: '55vh',
        width: '60%',
        submit: '支付并批量发布活动',
        close: ''
      }"
      @normal-submit="submitDialogPrice"
      >
      <template #dialog-content v-if="$refs[`dialog-price`] && $refs[`dialog-price`].showDialog">
        <div class="price-dialog-content flex-column">
          <span class="dialog-title">活动明细</span>
          <div class="row-item flex-normal gb">
            <div class="col-item flex-normal">
              <span class="col-label">技术服务费</span>
              <span class="col-label">{{dialogPrice['serveFee'] || '0.00'}}元</span>
            </div>
            <div class="col-item flex-normal">
              <span class="col-label">核销总计</span>
              <span class="col-label">{{dialogPrice['writeOffFee'] || '0.00'}}元</span>
            </div>
          </div>
          <div class="row-item flex-normal">
            <div class="col-item flex-normal">
              <span class="col-label">免付金额</span>
              <span class="col-label">{{dialogPrice['freePaymentAmount'] || '0.00'}}元</span>
            </div>
            <div class="col-item flex-normal">
              <span class="col-label">合计应付</span>
              <span class="col-label">{{dialogPrice['payableAmount']}}元</span>
            </div>
          </div>
        </div>
        <div class="LPay-code-container">
          <div class="flex-normal">
            <span class="Lpay-label">支付密码：</span>
            <div id="ipt_pwd" class="flex-normal ipt-pwd-content">
              <span id="LOGPASS_SHOW" class="placehoder-txt">请输入支付密码</span>
              <input id="LOGPASS" class="default input_search" type="password" disabled="disabled" />
              <div id="keyboardBtn" class="ipt_pwd_rjp default"></div>
            </div>
          </div>
        </div>
      </template>
    </dialog-normal>
    <dialog-normal
      ref="dialog-zhyz"
      :dialog-prop="{
        title: '账户验证',
        width: '500px',
        submit: '立即发布',
        close: '取消'
      }"
      @normal-submit="submitDialogCode">
      <template #dialog-content v-if="$refs[`dialog-zhyz`] && $refs[`dialog-zhyz`].showDialog">
        <el-input placeholder="请输入手机验证码" v-model="telCode"></el-input>
      </template>
    </dialog-normal>
  </div>
</template>

<script>
import {
  getActivityList, getH5Link, stopActivity, delActivity, batchPrice, batchPay
} from "@/api/activeManage/active";
import {LLKeyBord} from '@/utils/tools.js'
import {
  getRandom
} from "@/api/financeManage/lpay.js";
import { mapActions } from 'vuex'
export default {
  name: "StoreActiveList",
  components: {
    "search-header": () => import("@/rhComponents/searchHeader/index"),
    "dialog-normal": () => import("@/rhComponents/dialog/normal-dialog"),
  },
  filters: {
    numToStr(num, list, type){
      let index = list.findIndex(item => item.name == type)
      if(index == -1) return '未定义参数'
      let idx = list[index].child.findIndex(i => i.dictValue == num)
      if(idx == -1) return '未定义状态'
      return list[index].child[idx].dictLabel
    }
  },
  data() {
    return {
      selectProp: JSON.parse(JSON.stringify(this.$getSearchHeader(this))),
      boo: {
        loading: false, // 遮罩层
        showSearch: true, // 显示搜索条件
        multiple: true, // 非多个禁用
      },
      other: {
        ids: [], // 选中数组
        total: 0, //总条数
      },      
      dictsList: [],
      // 地块列表
      list: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      linkProp: {
        currentItem: {}
      },
      dialogPrice: {},
      LPayProp: {
        options: {},
        passwordInstance: null
      },
      telCode: '',
    };
  },
  mounted(){
    let _self = this
    _self.initGetDicts().then(res => {
      _self.getList()
    })
  },
  methods: { 
    ...mapActions(['setActivity', 'setdrawingH5']),
     // 非未支付状态 不能勾选
     selectEnable(row, rowIndex) {
      if (row.activityStatus != 3) return false;
      return true;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.other.ids = selection.map((item) => item.id);
      this.boo.multiple = !selection.length;
    },
    async getRandom(){
      let _self = this, isSuccess = false
      await getRandom().then(res => {
        _self.LPayProp.options = res.data
        isSuccess = true
      })
      return isSuccess
    },
    initPassword() {
      let _self = this
      setTimeout(() => {
        let paramsPwd = {
          click_objId: '#keyboardBtn',
          Input_texId: '#LOGPASS',
          parent_objId: '#ipt_pwd',
          placeholderId: '#LOGPASS_SHOW'
        }
        const passowrd = LLKeyBord(paramsPwd, _self.LPayProp.options)          
        passowrd.initOptions()
        _self.LPayProp.passwordInstance = passowrd
      })
    },
    // 获取批量总价
    async fetchBatchPrice(){
      let _self = this
      let ids = this.other.ids || []
      this.$modal
        .confirm('是否确认批量支付选中活动？')
        .then(async function () {
          await _self.getRandom()
          await batchPrice({
            activityIds: ids
          }).then(res => {
            _self.dialogPrice = res.data
            _self.$refs['dialog-price'].showDialog = true
            _self.initPassword()
          })
        })
        .catch(() => {});
    },
    
    async submitDialogPrice(){
      let _self = this
      let {passwordInstance, options} = _self.LPayProp
      let vm = _self.$refs['dialog-price']
      // 获取国密密文
      passwordInstance.setRandKey(options.random_value) // 先设置随机key
      const password = passwordInstance.getOutputSM() // 国密加密密码
      const hash = passwordInstance.getHash() // RSA加密密码
      if(!hash || hash == '') {
        vm.loading = false
        return _self.$message.error('密码不能为空')
      }

      let props = {
        password: password,
        random_key: _self.LPayProp.options['random_key'],
        activityIds: _self.other.ids ?? []
      }
      batchPay(props).then(res => {
        const { code } = res
        if(code == 600){
          _self.$refs['dialog-zhyz'].showDialog = true
        }else{
          vm.showDialog = false
          _self.getList()
          _self.$message.success('操作成功')
        }
      }).catch(err => {
        _self.getRandom()
      }).finally(() => {
        vm.loading = false
      })
    },
    async submitDialogCode(){
      let _self = this
      let vm = _self.$refs['dialog-zhyz']
      if(!_self.telCode || _self.telCode == '') {
        vm.loading = false
        return _self.$message.error('验证码不能为空')
      }
      let props = {
        code: _self.telCode,
        activityIds: _self.other.ids ?? []
      }
      batchPay(props).then(res => {
        vm.showDialog = false
        _self.$message.success('操作成功')
        _self.getList()
      }).finally(() => {
        vm.loading = false
      })
    },
    hasDetailBtn(row){
      let {activityTypeId, activityStatus} = row, boo = false
      if(['2', '3', '4', '7'].includes(`${activityTypeId}`) && ['1'].includes(`${activityStatus}`)){
        boo = true
      }
      return true
    },
    hasEditBtn(row){
      let {activityTypeId, activityStatus} = row, boo = false
      if(['2', '3', '4', '7'].includes(`${activityTypeId}`) && ['0', '1'].includes(`${activityStatus}`)){
        boo = true
      }
      return boo
    },
    // 判断当前活动类型是否只支持h5配置
    hasH5(row){
      let {activityTypeId} = row, boo = false
      if(activityTypeId == '2' || activityTypeId == '3' || activityTypeId == '4'  || activityTypeId == '7'){
        boo = true
      }
      return boo
    },
    /** 复制代码成功 */
    clipboardSuccess() {
      this.$modal.msgSuccess("复制成功");
    },
    jumpPage(name, query = {}, params = {}){
      let _self = this
      _self.setdrawingH5({draw: []}).then(res => {
        _self.$router.push({name, params, query})
      })      
    },
    // 搜索条件查询
    searchAction(prop) {
      this.queryParams = Object.assign(this.queryParams, prop["params"]);
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 查询用户列表 */
    getList() {
      this.boo.loading = true;
      getActivityList(this.queryParams)
        .then((response) => {
          this.list = response.rows;
          this.other.total = response.total;
          this.boo.loading = false;
        })
        .catch(() => {});
    },    
    // 事件集合 -- 转发
    actionsMaps(ref, acion, row){
      let _self = this
      let actionsMap = () => {
        return new Map([
          [{ref: 'link', acion: 'view:show'}, ()=>{
            _self.$set(row, 'isLink', true)
            getH5Link(row.id).then(res => {
              _self.linkProp.currentItem = res.data
              _self.$set(_self.linkProp.currentItem, 'activityTypeId', row.activityTypeId)
              _self.$nextTick(() => {
                _self.$refs[`dialog-${ref}`].showDialog = true
              })
            }).finally(() => _self.$set(row, 'isLink', false))
          }],
        ])
      }
      let actions = [...actionsMap()].filter(([key,value])=>(key.ref == ref && key.acion == acion))
      actions.forEach(([key,value])=>value.call(this))
    },
    showDialog(ref, type, row) {
      let _self = this;
      if (_self.$refs[`${ref}-form`]) {
        this.resetForm(`${ref}-form`);
      }
      _self.$nextTick(() => {
        _self.actionsMaps(ref, `${type}:show`, row)
      })
    },
    /** 终止按钮操作 */
    stopRow(row) {
      this.$modal
        .confirm('是否确认停止？')
        .then(function () {
          return stopActivity(row.id);
        })
        .then(() => {
          this.queryParams.pageNum = 1
          this.getList();
          this.$modal.msgSuccess("停止成功");
        })
        .catch(() => {});
    },
    /** 终止按钮操作 */
    delRow(row) {
      this.$modal
        .confirm('是否确认删除？')
        .then(function () {
          return delActivity(row.id);
        })
        .then(() => {
          this.queryParams.pageNum = 1
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  }
};
</script>
<style scoped lang="scss">
.dialog-link-content{
  .item-row{
    margin-bottom: 20px;
    &.img{
      align-items: flex-start;
    }
    .row-label{
      color: #3E3E3E;
      font-size: 13px;
      width: 120px;
    }
    .row-btn{
      margin-left: 30px;
    }
    .row-content{
      padding: 8px 0;
      border-bottom: 1px solid #D8D8D8;
      color: #3D3D3D;
      font-size: 13px;
    }
    .row-img{
      width: 100px;
    }
  }
}
.price-dialog-content{
  .dialog-title{
    font-size: 16px;
    color: #0003AA;
  }
  .row-item{
    margin-top: 15px;
    &.gb{
      margin-top: 30px;
    }
    .col-item {
      width: 50%;
      .col-label{
        font-size: 13px;
        color: #3D3D3D;
        width: 50%;
      }
    }
  }
}
.LPay-code-container ::v-deep{
  .ipt-pwd-content{
    height: 60px;
    position: relative;
    width: 60%;
    border-bottom: 1px solid #D8D8D8;
    margin-bottom: 10px;
    .placehoder-txt{
      color: #999;
      font-size: 13px;
    }
  }
  .Lpay-label{
    font-size: 13px;
    width: 120px;
  }
}
</style>